<template>
  <a-row :gutter="24" class="search-row">
    <a-col :span="24">
      <x-card>
        <div slot="content" class="table-page-search-wrapper">
          <a-form layout="inline">
            <a-row :gutter="48">
              <a-col :span="7">
                <a-form-item label="数据来源" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-select
                    allow-clear
                    placeholder="请选择数据来源"
                    v-model="selectedCheckTypes"
                    mode="multiple"
                    @change="handleCheckTypeChange"
                    style="height: 40px; overflow-y: auto"
                  >
                    <a-select-option value="全部">全部</a-select-option>
                    <a-select-option v-for="item in CheckTypeList" :key="item.id" :value="item.item">{{
                      item.item
                    }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="7">
                <a-form-item label="检查时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-date-picker
                    style="width: 100%"
                    format="YYYY-MM-DD"
                    @change="onChange1"
                    :style="{ width: '50%' }"
                    v-model="TimeOn"
                  />
                  <a-date-picker
                    style="width: 100%"
                    format="YYYY-MM-DD"
                    @change="onChange2"
                    :style="{ width: '50%' }"
                    v-model="TimeEnd"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="7">
                <a-form-item label="违章单位" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-tree-select
                    allowClear
                    showSearch
                    style="scroll: true"
                    tree-node-filter-prop="title"
                    v-model="queryParam.organizationName"
                    :treeData="QHSEOrganizationTree"
                    v-if="QHSEOrganizationTree.length"
                    @change="onChangeVioData"
                    :defaultExpandAll="true"
                    :defaultExpandedKeys="defaultExpandedKeys"
                    :replaceFields="replaceFields"
                    ref="tree"
                    placeholder="请选择隐患单位"
                  />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="48" >
              <a-col :span="7">
                <a-form-item label="违章性质" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-select
                    allow-clear
                    placeholder="请选择违章性质"
                    v-model="selectedViolationType"
                    @change="handlViolationTypeSelectChange"
                    mode="multiple"
                    style="height: 40px; overflow-y: auto;">
                    <a-select-option value="全部">全部</a-select-option>
                    <a-select-option
                      v-for="item in ViolationTypeList"
                      :key="item.violationTypeId"
                      :value="item.violationType">{{
                        item.violationType
                      }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="7">
                <a-form-item label="作业专业" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-select
                    allow-clear
                    placeholder="请选择作业专业"
                    style="height: 40px; overflow-y: auto"
                    v-model="selectedWorkSpecialty"
                    @change="handleZYZYSelectChange"
                  >
                    <a-select-option
                      v-for="item in QHSEKeyWorkSpecialtyList"
                      :key="item.id"
                      :value="item.specialty"
                      :code="item.specialtyCode"
                    >{{ item.specialty }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="7">
                <a-form-item label="重复数量>" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input v-model="queryParam.repeat" allow-clear/>
                </a-form-item>
              </a-col>
              <a-col :span="3" class="search-buttons">
                <a-button type="primary" @click="handleClick" v-if="hasPerm('hdv_qhse_v_cfxwz')">查询</a-button>
                <a-button style="margin-left: 6px" @click="reset">重置</a-button>
              </a-col>
            </a-row>
          </a-form>
        </div>
      </x-card>
      <a-card :bordered="false">
        <a-row>
          <a-col :span="8">
            <a-table
              bordered
              ref="table"
              :columns="columns"
              :dataSource="loadData"
              :pagination="false"
              :alert="false"
              :rowKey="(record, index) => index"
            ></a-table>
          </a-col>
          <a-col :span="16" :style="{ visibility: showEcharts ? 'visible' : 'hidden' }">
            <div id="bar-chart-container" style="width: 100%;"></div>
          </a-col>
        </a-row>
        <!-- <s-table
          ref="table"
          :columns="columns"
          :data="loadData"
          :alert="null"
          :rowKey="(record) => record.QhseXyDangerId"
          :rowSelection="null"
          :pagination="false"
        >
        </s-table>-->
      </a-card>
    </a-col>
  </a-row>
</template>
<script>
import { STable, XCard, XDown } from '@/components'
import { Empty } from 'ant-design-vue'
import { getQHSEXyViolationTypeList, vioRepeat } from '@/api/modular/system/QHSEXyViolation'
import { getQHSECheckTypeList } from '@/api/modular/system/QHSEHazardQuery'
import { getQHSEOrganizationTree } from '@/api/modular/system/QHSEOrganization'
import { getQHSEKeyWorkSpecialtyList } from '@/api/modular/system/QHSEKeyWork'
import * as echarts from 'echarts'
import moment from 'moment'
import { mapGetters } from 'vuex'
export default {
  components: {
    XDown,
    XCard,
    STable
  },
  data() {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      // 查询参数
      TimeEnd: moment(new Date(), 'YYYY-MM-DD'),
      TimeOn: moment(new Date(), 'YYYY-MM-DD').subtract(1, 'months'),
      // 表头
      columns: [
        {
          title: '序号',
          customRender: (text, record, index) => `${index + 1}`
        },
        {
          title: '违章性质',
          dataIndex: 'ViolationType'
        },
        {
          title: '重复数量',
          dataIndex: 'Repeat'
        }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: [],
      queryParam: {
        TimeOn: moment(new Date()).subtract(1, 'months').format('YYYY-MM-DD'),
        TimeEnd: moment(new Date()).format('YYYY-MM-DD') + 'T' + moment().format('23:59:59')
      },
      selectedKeys: [],
      selectedCheckTypes: [],
      selectedViolationType: [],
      selectedWorkSpecialty: [],
      QHSEKeyWorkSpecialtyList: [],
      CheckTypeList: [],
      // selectedRowKeys: [],
      selectedRows: [],
      defaultExpandedKeys: [],
      sexDictTypeDropDown: [],
      statusDictTypeDropDown: [],
      QHSEOrganizationTree: [],
      ViolationTypeList: [],
      simpleImage: Empty.PRESENTED_IMAGE_SIMPLE,
      replaceFields: {
        children: 'children',
        title: 'title',
        key: 'workflowId',
        value: 'id',
        parentId: 'parentId'
      },
      HazardLevelList: [],
      HazardStatusList: [],
      showEcharts: true,
      secondOraName: {
          id: ''
        }
    }
  },
  created() {
    this.getQHSEOrganizationTree()
    this.getQHSEKeyWorkSpecialtyList()
    this.getQHSECheckTypeList()
    this.getQHSEXyViolationTypeList()
  },
  computed: {
      ...mapGetters(['userInfo'])
      },
  methods: {
    renderBarChart(data, containerId, chartType) {
      const barChartContainer = document.getElementById(containerId)
      const barChart = echarts.init(barChartContainer)
      const barChartData = this.loadData.map(item => ({
        value: item.Repeat,
        name: item.ViolationType
      }))
      console.log('barChartData', barChartData)
      const barChartOptions = {
        title: {
          text: '',
          textStyle: {
            fontWeight: 'bold',
            fontSize: 20
          },
          left: 'center' // 标题水平居中
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          containLabel: true,
          top: 60
        },
        xAxis: {
          type: 'category',
          data: null,
          axisLabel: {
            interval: 0,
            fontSize: 14
          }
        },
        yAxis: {
          type: chartType === 'vertical' ? 'value' : 'category',
          data: null
        },
        series: [
          {
            type: 'bar',
            data: barChartData,
            barWidth: '40%'
          }
        ]
      }
      if (containerId === 'bar-chart-container') {
        barChartOptions.title.text = '违章性质'
        barChartOptions.xAxis.type = 'value'
        barChartOptions.yAxis.data = barChartData.map(item => item.name)
        barChartOptions.yAxis.axisLabel = {
          interval: 0,
          fontSize: 14 // 设置较大的字体大小
        }
        barChartOptions.series = [
          {
            type: 'bar',
            data: barChartData,
            barWidth: '25%' // 设置较小的值，使柱子变细
          }
        ]
        }
      if (barChartData.length > 0) {
        barChart.setOption(barChartOptions)
      }
    },
    handleClick() {
      if ((!this.TimeOn && !this.TimeEnd) || (this.TimeOn && this.TimeEnd)) {
        vioRepeat(this.queryParam).then((res) => {
            this.loadData = res
            if (res.length === 0) {
                this.showEcharts = false
            } else {
                this.showEcharts = true
                const tableElement = document.getElementById('bar-chart-container')
                tableElement.style.height = 100 + (53.8 * (res.length + 2)) + 'px'
                this.renderBarChart(res, 'bar-chart-container', 'value')
            }
        })
      } else {
        // 提示用户需要填写完整的时间信息
        this.$message.warning('请填写完整的时间信息')
      }
    },
    onChange1(date, dateString) {
      console.log(dateString, date)
      if (this.queryParam.TimeEnd && dateString) {
        if (dateString > this.queryParam.TimeEnd) {
          this.$message.error('开始时间不能晚于结束时间')
          this.TimeEnd = moment(new Date(), 'YYYY-MM-DD')
          this.TimeOn = moment(new Date(), 'YYYY-MM-DD').subtract(1, 'months')
          this.queryParam.TimeOn = moment(new Date()).subtract(1, 'months').format('YYYY-MM-DD')
          this.queryParam.TimeEnd = moment(new Date()).format('YYYY-MM-DD')
        } else {
          this.queryParam.TimeOn = dateString
        }
      } else {
        this.queryParam.TimeOn = dateString
      }
    },
    onChange2(date, dateString) {
      if (this.queryParam.TimeOn && dateString) {
        if (this.queryParam.TimeOn > dateString) {
          this.$message.error('开始时间不能晚于结束时间')
          this.TimeEnd = moment(new Date(), 'YYYY-MM-DD') + 'T' + moment().format('23:59:59')
          this.TimeOn = moment(new Date(), 'YYYY-MM-DD').subtract(1, 'months')
          this.queryParam.TimeOn = moment(new Date()).subtract(1, 'months').format('YYYY-MM-DD')
          this.queryParam.TimeEnd = moment(new Date()).format('YYYY-MM-DD') + 'T' + moment().format('23:59:59')
        } else {
          this.queryParam.TimeEnd = dateString + 'T' + moment().format('23:59:59')
        }
      } else {
        this.queryParam.TimeEnd = dateString + 'T' + moment().format('23:59:59')
      }
    },
    statusFilter(status) {
      // eslint-disable-next-line eqeqeq
      const values = this.QHSEOrgnizationTree.filter((item) => item.code === status)
      if (values.length > 0) {
        return values[0].value
      }
    },
    getQHSEOrganizationTree () {
      this.secondOraName.id = this.userInfo.secondOrganizationName
      getQHSEOrganizationTree(Object.assign(this.secondOraName)).then(res => {
      this.treeLoading = false
      if (!res.success) {
          return
      }
      this.QHSEOrganizationTree = res.data
      if (res.data.length === 0) {
          this.secondOraName.id = '机关总部'
          getQHSEOrganizationTree(Object.assign(this.secondOraName)).then(res => {
            this.QHSEOrganizationTree = res.data
          })
        }
     })
    },
    getQHSEKeyWorkSpecialtyList(text) {
      getQHSEKeyWorkSpecialtyList().then((res) => {
        this.QHSEKeyWorkSpecialtyList = res.data
       })
    },
    getQHSECheckTypeList(text) {
      getQHSECheckTypeList().then((res) => {
        this.CheckTypeList = res.data // 将后端返回的数据赋值给 CheckTypeList
        //  console.log(this.CheckTypeList)
      })
    },
    getQHSEXyViolationTypeList(text) {
      getQHSEXyViolationTypeList().then((res) => {
        this.ViolationTypeList = res.data
      })
    },
    onChangeVioData(value, label, extra) {
      // console.log(value, label, extra)
      if (extra.triggerNode === undefined) {
        this.queryParam.organizationName = null
        this.queryParam.organizationId = null
      } else {
        this.queryParam.organizationName = extra.triggerNode._props.title
        this.queryParam.organizationId = extra.triggerNode._props.value
      }
    },
    handleCheckTypeChange(value) {
      if (value.includes('全部')) {
        // 选中了全部选项，将所有选项都添加到 selectedCheckTypes 中
        this.selectedCheckTypes = this.CheckTypeList.map((item) => item.item)
      }
      this.queryParam.checkTypes = this.selectedCheckTypes.map((option) => option.toString())
    },
    handleDangerType(value) {
      if (value.includes('全部')) {
        // 选中了全部选项，将所有选项都添加到 selectedCheckTypes 中
        this.selectedDangerType = this.HazardLevelList.map(item => item.item)
      } // 取消选中全部选项，更新 selectedCheckTypes
        this.queryParam.dangerTypes = [...this.selectedDangerType]
    },
    handleZYZYSelectChange(value, option) {
      this.queryParam.workSpeciality = this.selectedWorkSpecialty
    },
    handlViolationTypeSelectChange(value, option) {
      if (value.includes('全部')) {
        this.selectedViolationType = this.ViolationTypeList.map(item => item.violationType)
      }
      this.queryParam.violationTypes = [...this.selectedViolationType]
    },
    reset() {
      this.selectedCheckTypes = []
      this.selectedViolationType = []
      this.selectedWorkSpecialty = []
      this.queryParam = {
        TimeOn: moment(new Date()).subtract(1, 'months').format('YYYY-MM-DD'),
        TimeEnd: moment(new Date()).format('YYYY-MM-DD')
      }
      this.TimeEnd = moment(new Date(), 'YYYY-MM-DD')
      this.TimeOn = moment(new Date(), 'YYYY-MM-DD').subtract(1, 'months')
    }
  }
}
</script>
<style lang="less" scoped>
.table-operator {
  margin-bottom: 18px;
}
button {
  margin-right: 8px;
}
.search-row {
  display: flex;
  align-items: center;
}

.search-buttons {
  display: flex;
  justify-content: flex-end;
}
</style>
